package com.alibaba.dongbao.utils.filet;

import com.alibaba.dongbao.base.result.Result;
import com.alibaba.dongbao.utils.BodyReaderHttpServletRequestWrapper;
import com.alibaba.dongbao.utils.HttpParamUtil;
import com.alibaba.dongbao.utils.SignUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.SortedMap;

/**
 * @Author: Mr.ZJW
 * @Date: 2022-05-06 9:17
 * @Description: Sign过滤器
 */
@Slf4j
//@Component
public class SignAuthFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //ServletRequest转HttpServletRequest
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        //获取请求路径
        final String uri = req.getRequestURI().startsWith("/") ? req.getRequestURI().substring(1) : req.getRequestURI();
        //对以下请求放行
        if(uri.contains("user/getCaptcha")){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //转HttpServletRequest以及HttpServletResponse
        HttpServletRequest request = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) servletRequest);
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求参数工具类，包括是get或post
        SortedMap<String, Object> allParams = HttpParamUtil.getAllParams(request);
        log.info("所有请求参数:{}", allParams);
        //校验签名
        Boolean flag = SignUtil.checkSign(allParams);
        if (flag){
            filterChain.doFilter(request, response);
        }else {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg","签名不正确");
            jsonObject.put("code",-1);
            writer.println(jsonObject);
        }
    }

    @Override
    public void destroy() {
    }

}
